/**
 * 
 */
package org.libermundi.theorcs.chronicles.tapestry.components;

import java.util.ArrayList;
import java.util.List;

import org.apache.tapestry5.SelectModel;
import org.apache.tapestry5.annotations.InjectComponent;
import org.apache.tapestry5.annotations.Log;
import org.apache.tapestry5.annotations.Parameter;
import org.apache.tapestry5.annotations.Property;
import org.apache.tapestry5.annotations.SessionState;
import org.apache.tapestry5.annotations.SetupRender;
import org.apache.tapestry5.corelib.components.Zone;
import org.apache.tapestry5.ioc.annotations.Inject;
import org.apache.tapestry5.services.SelectModelFactory;
import org.libermundi.theorcs.chronicles.dto.ChronicleSettings;
import org.libermundi.theorcs.chronicles.model.Dice;
import org.libermundi.theorcs.chronicles.model.Persona;
import org.libermundi.theorcs.chronicles.services.AddressBookManager;
import org.libermundi.theorcs.chronicles.services.DiceService;


/**
 * Ajax component to roll a dice
 *
 */
public class DiceRollerForm {

	@Property
	@Parameter
	private int diceNumber,diceType, difficulty;

	@Property
	@Parameter
	private String reason;
	
	//TODO a utiliser avec le RuleEngine 
	@Parameter 
	private boolean strictlyMore = false;
	
	//Result of the roll, need a dice property to be used in the .tml
	@Property
	private List<Dice> dices;
	@Property
	private Dice dice;
	
	//AjaxComponent
	@InjectComponent
	private Zone diceRollerZone;
	
	@Inject
	private DiceService diceService;
	
	@Inject
	private AddressBookManager _addressBookManager;
	
	@SessionState
	private ChronicleSettings chronicleSettings;
		
	@Property
	private SelectModel personaSelectModel;
	
	@Inject
	SelectModelFactory personaModelFactory;
	
	@Property
	@Parameter
	Persona dest;
	
	@SetupRender
	void init(){
		diceNumber=1;
		diceType=10;
		// get all the contacts of the caster
		Persona caster = chronicleSettings.getPersona();
		List<Persona> contacts = _addressBookManager.loadAddressBook(caster).getContactsAsList();
	    // create a SelectModel from the list of contacts
	    personaSelectModel = personaModelFactory.create(contacts, "name");
	}
	
	@Log
	Object onSuccess(){
		// Get the persona who rolls the dices
		// Persona caster = chronicleSettings.getPersona(); // Not Used
		// Make as many dices as needed
		dices = new ArrayList<>(diceNumber);
		for (int i=0;i<diceNumber;i++){
			Dice dice = new Dice(diceType, null);
			diceService.throwDice(dice, difficulty, strictlyMore);
			dices.add(dice);
		}
		//the zone is the ajax html item to be updated
		return diceRollerZone.getBody();
	  }

}
